package com.ca.project.Server.Modules.RepairInfo.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ca.project.Server.Modules.RepairImg.Entity.RepairImg;
import com.ca.project.Server.Modules.RepairImg.Service.RepairImgService;
import com.ca.project.Server.Modules.RepairInfo.Context.AcceptRepairInfoContext;
import com.ca.project.Server.Modules.RepairInfo.Context.CreateRepairInfoContext;
import com.ca.project.Server.Modules.RepairInfo.Converter.RepairInfoConverter;
import com.ca.project.Server.Modules.RepairInfo.DTO.RepairInfoDTO;
import com.ca.project.Server.Modules.RepairInfo.Entity.RepairInfo;
import com.ca.project.Server.Modules.RepairInfo.Service.RepairInfoService;
import com.ca.project.Server.Modules.RepairInfo.Mapper.RepairInfoMapper;
import com.ca.project.Server.Modules.UserInfo.Entity.UserInfo;
import com.ca.project.Server.Modules.UserInfo.Service.UserInfoService;
import com.ca.project.core.Exception.BusinessException;
import com.ca.project.core.Util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author ASUS
 * @description 针对表【repair_info】的数据库操作Service实现
 * @createDate 2025-01-03 15:14:50
 */
@Service
public class RepairInfoServiceImpl extends ServiceImpl<RepairInfoMapper, RepairInfo> implements RepairInfoService {

    @Autowired
    private RepairInfoConverter repairInfoConverter;
    @Autowired
    private RepairImgService repairImgService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 创建维修订单
     *
     * @param createRepairInfoContext
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(CreateRepairInfoContext createRepairInfoContext) {
        doFindOpenid(createRepairInfoContext);
        assembleRepairInfo(createRepairInfoContext);
        doCreate(createRepairInfoContext);
    }


    /**
     * 删除维修订单
     *
     * @param rId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String rId) {
        RepairInfo entity = findRepairInfo(rId);
        if (Objects.isNull(entity))
            throw new BusinessException("没有改订单");
        Object list = entity.getRImgList();
        if (list instanceof String && !list.toString().trim().isEmpty()) {
            try {
                JSONArray jsonArray = JSON.parseArray(list.toString());
                if (jsonArray != null && !jsonArray.isEmpty())
                    repairImgService.deleteImg(list);
            } catch (Exception e) {
                throw new BusinessException("维修图片解析失败");
            }
        }
        QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("r_id", rId);
        boolean success = baseMapper.delete(wrapper) > 0;
        if (!success)
            throw new BusinessException("删除失败");
    }

    /**
     * 维修人员接单
     *
     * @param acceptRepairInfoContext
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void accept(AcceptRepairInfoContext acceptRepairInfoContext) {
        doCheckRepairInfo(acceptRepairInfoContext);
        doValid(acceptRepairInfoContext);
        doAccept(acceptRepairInfoContext);
    }


    /**
     * 返回待处理订单
     * 1.检查openid是用户还是维修者
     * 2.检索出对应的订单
     *
     * @param token
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<RepairInfo> getPending(String token) {
        UserInfo entity = userInfoService.find(token);
        if (Objects.isNull(entity))
            throw new BusinessException("该维修人员不存在");
        System.out.println(entity.getRepairId());
        if (entity.getRepairId() == 0) {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_openid", entity.getOpenid())
                    .eq("r_state", 0);
            return baseMapper.selectList(wrapper);
        } else {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_state", 0);
            return baseMapper.selectList(wrapper);
        }
    }

    /**
     * 返回已完成订单
     *
     * @param token
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<RepairInfo> getFinish(String token) {
        UserInfo entity = userInfoService.find(token);
        if (Objects.isNull(entity))
            throw new BusinessException("该维修人员不存在");
        if (entity.getRepairId() == 0) {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_openid", entity.getOpenid())
                    .eq("r_state", 2);
            return baseMapper.selectList(wrapper);
        } else {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_state", 2)
                    .eq("r_bm_openid", entity.getOpenid());
            return baseMapper.selectList(wrapper);
        }
    }

    /**
     * 返回该用户所有订单
     *
     * @param token
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<RepairInfo> getInfo(String token) {
        UserInfo entity = userInfoService.find(token);
        if (Objects.isNull(entity))
            throw new BusinessException("该用户不存在");
        QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("r_openid", entity.getOpenid());
        return baseMapper.selectList(wrapper);
    }

    /**
     * 返回特定的订单信息
     * 1.需要通过id找到用户的openid
     * 2.并带出用户信息
     * 3.然后再把图片集合的url找出来
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RepairInfoDTO getSpecificInfo(String id) {
        RepairInfo entity = findRepairInfo(id);
        if (Objects.isNull(entity))
            throw new BusinessException("没有改订单信息");
        UserInfo userInfo = userInfoService.getInfo(entity.getROpenid());
        //List<String> imgList = repairImgService.findImg(entity.getRImgList());
        RepairInfoDTO repairInfoDTO = new RepairInfoDTO();
        repairInfoDTO.setRepair_info(entity);
        repairInfoDTO.setUser_info(userInfo);
        //repairInfoDTO.setRepair_img(imgList);
        return repairInfoDTO;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @param repairInfo
     * @return
     */
    @Override
    public IPage<RepairInfo> getPage(Integer currentPage, Integer pageSize, RepairInfo repairInfo) {
        LambdaQueryWrapper<RepairInfo> wrapper = new LambdaQueryWrapper<>();
        IPage<RepairInfo> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public IPage<RepairInfo> getPage(Integer currentPage, Integer pageSize) {
        IPage<RepairInfo> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, null);
        return page;
    }

    /**
     * 获取已接单
     *
     * @param token
     * @return
     */
    @Override
    public List<RepairInfo> getAccept(String token) {
        UserInfo entity = userInfoService.find(token);
        if (Objects.isNull(entity))
            throw new BusinessException("该维修人员不存在");
        if (entity.getRepairId() == 0) {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_openid", entity.getOpenid())
                    .eq("r_state", 1);
            return baseMapper.selectList(wrapper);
        } else {
            QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("r_state", 1)
                    .eq("r_bm_openid", entity.getOpenid());
            return baseMapper.selectList(wrapper);
        }
    }

    /**
     * 完成订单
     *
     * @param acceptRepairInfoContext
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(AcceptRepairInfoContext acceptRepairInfoContext) {
        doCheckRepairInfo(acceptRepairInfoContext);
        doValid(acceptRepairInfoContext);
        doFinish(acceptRepairInfoContext);
    }

/************************************************private***************************************************************/

    /**
     * 实体转换
     *
     * @param createRepairInfoContext
     */
    private void assembleRepairInfo(CreateRepairInfoContext createRepairInfoContext) {
        RepairInfo entity = repairInfoConverter.CreateRepairInfoContext2RepairInfo(createRepairInfoContext);
        String r_img_list = JSON.toJSONString(createRepairInfoContext.getR_img_list());
        final Long id = IdUtil.get();
        entity.setRId(id);
        entity.setROpenid(createRepairInfoContext.getR_openid());
        entity.setRPcType(createRepairInfoContext.getR_pc_type());
        entity.setRPcName(createRepairInfoContext.getR_pc_name());
        entity.setRReason(createRepairInfoContext.getR_reason());
        entity.setRImgList(r_img_list);
        entity.setRReserveTime(createRepairInfoContext.getR_reserve_time());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());

        createRepairInfoContext.setEntity(entity);

    }

    /**
     * 创建维修单实体
     *
     * @param createRepairInfoContext
     */
    private void doCreate(CreateRepairInfoContext createRepairInfoContext) {
        RepairInfo entity = createRepairInfoContext.getEntity();
        if (entity == null)
            throw new BusinessException("维修单实体不能为空");
        try {
            if (!save(entity))
                throw new BusinessException("维修单实体创建失败");
        } catch (Exception e) {
            throw new BusinessException("维修单实体创建失败,原因:" + e.getMessage());
        }
    }

    /**
     * 查找订单信息
     *
     * @param rId
     * @return
     */
    private RepairInfo findRepairInfo(String rId) {
        QueryWrapper<RepairInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("r_id", rId);
        return getOne(wrapper);
    }

    /**
     * 找订单是否存在
     *
     * @param acceptRepairInfoContext
     */
    private void doCheckRepairInfo(AcceptRepairInfoContext acceptRepairInfoContext) {
        String rId = acceptRepairInfoContext.getR_id();
        RepairInfo entity = findRepairInfo(rId);
        if (Objects.isNull(entity))
            throw new BusinessException("该订单不存在");
    }

    /**
     * 维修人员接单
     *
     * @param acceptRepairInfoContext
     */
    private void doAccept(AcceptRepairInfoContext acceptRepairInfoContext) {
        UpdateWrapper<RepairInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("r_id", acceptRepairInfoContext.getR_id())
                .set("r_bm_openid", acceptRepairInfoContext.getOpenid())
                .set("r_state", 1)
                .set("update_time", new Date());
        baseMapper.update(null, wrapper);
    }

    /**
     * 传入token找openid
     *
     * @param acceptRepairInfoContext
     */
    private void doValid(AcceptRepairInfoContext acceptRepairInfoContext) {
        UserInfo entity = userInfoService.find(acceptRepairInfoContext.getToken());
        if (Objects.isNull(entity))
            throw new BusinessException("该维修人员不存在");
        acceptRepairInfoContext.setOpenid(entity.getOpenid());
    }

    /**
     * 传入token找openid
     *
     * @param createRepairInfoContext
     */
    private void doFindOpenid(CreateRepairInfoContext createRepairInfoContext) {
        UserInfo entity = userInfoService.find(createRepairInfoContext.getToken());
        if (Objects.isNull(entity))
            throw new BusinessException("该用户不存在");
        createRepairInfoContext.setR_openid(entity.getOpenid());
    }

    /**
     * 完成顶单
     *
     * @param acceptRepairInfoContext
     */
    private void doFinish(AcceptRepairInfoContext acceptRepairInfoContext) {
        UpdateWrapper<RepairInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("r_id", acceptRepairInfoContext.getR_id())
                .set("r_bm_openid", acceptRepairInfoContext.getOpenid())
                .set("r_state", 2)
                .set("update_time", new Date());
        baseMapper.update(null, wrapper);
    }
}




